const { Comment } = require("../models/comment");
const { Good } = require("../models/good");
const { AppUser } = require("../models/appUser");

// Create a new comment
exports.createComment = async (req, res) => {
  try {
    const { goodId, detail } = req.body;
    const appUserId = req.userId;

    const newComment = await Comment.create({
      appUserId,
      goodId,
      detail,
    });

    res.status(200).json({
      message: "Comment created successfully",
      data: newComment,
      code: 200,
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// Get all comments
exports.getAllComments = async (req, res) => {
  try {
    const goodId = req.query.goodId;
    const comments = await Comment.findAll({
      where: goodId ? { goodId } : null,
      include: [
        Good,
        {
          model: AppUser,
          attributes: ["id", "name"],
        },
      ],
    });

    res.status(200).json({
      message: "All comments",
      data: comments,
      code: 200,
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// Get a single comment by ID
exports.getCommentById = async (req, res) => {
  try {
    const { id } = req.params;
    const comment = await Comment.findByPk(id, {
      include: [Good, AppUser],
    });

    if (!comment) {
      return res.status(404).json({ error: "Comment not found" });
    }

    res.status(200).json({
      message: "Comment found",
      data: comment,
      code: 200,
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// Update a comment
exports.updateComment = async (req, res) => {
  try {
    const { id } = req.params;
    const { detail } = req.body;

    const comment = await Comment.findByPk(id);

    if (!comment) {
      return res.status(404).json({ error: "Comment not found" });
    }

    comment.detail = detail;
    await comment.save();

    res.status(200).json({
      message: "Comment updated successfully",
      data: comment,
      code: 200,
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// Delete a comment
exports.deleteComment = async (req, res) => {
  try {
    const { id } = req.params;

    const comment = await Comment.findByPk(id);

    if (!comment) {
      return res.status(404).json({ error: "Comment not found" });
    }

    await comment.destroy();

    res.status(200).json({
      message: "Comment deleted successfully",
      comment,
      code: 200,
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};
